package com.hellogood.yaohuo.server.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hellogood.yaohuo.server.db.DBHelper;
import com.hellogood.yaohuo.shared.entity.Groupqx;
import com.hellogood.yaohuo.shared.exception.DatabaseException;

public class GroupQxDAO extends DBHelper {

	@Override
	public List<?> initializeObject(ResultSet rs) throws SQLException {
		List<Groupqx> list = new ArrayList<Groupqx>();
		if (rs != null) {
			while (rs.next()) {
				Groupqx qx = new Groupqx();
				qx.setGroupCode(rs.getString("GroupCode"));
				qx.setMkCode(rs.getString("MkCode"));
				list.add(qx);
			}
		}
		return list;
	}

	public List<Groupqx> getAllGroupqx() {
		String sql = "SELECT GroupCode,MkCode FROM Groupqx";
		List<?> list = super.query(sql);
		return (List<Groupqx>) list;
	}

	public Map<String, List<String>> getGroupqxMap() {
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		List<Groupqx> list = getAllGroupqx();
		for (Groupqx qx : list) {
			List<String> mks = map.get(qx.getGroupCode());
			if (mks == null) {
				mks = new ArrayList<String>();
			}
			if (!mks.contains(qx.getMkCode())) {
				mks.add(qx.getMkCode());
			}
			map.put(qx.getGroupCode(), mks);
		}
		return map;
	}

	public String addGroupqx(List<Groupqx> qxs) {
		String result = "";
		List<String> sqls = new ArrayList<String>();
		String sql = "DELETE FROM Groupqx";
		sqls.add(sql);
		for (Groupqx qx : qxs) {
			sql = "INSERT INTO Groupqx(GroupCode,MkCode) VALUES('" + qx.getGroupCode() + "','" + qx.getMkCode() + "')";
			sqls.add(sql);
		}
		try {
			super.executeBatch(sqls);
		} catch (DatabaseException e) {
			e.printStackTrace();
			result = e.getMessage();
		}
		return result;

	}

	public List<Groupqx> getGroupQxListByUsercode(String code) {
		String sql = "SELECT GroupCode,MkCode FROM GroupQx WHERE GroupCode IN (SELECT GroupCode FROM GroupUser WHERE StaffCode = '" + code + "')";

		List<?> list = super.query(sql);
		return (List<Groupqx>) list;

	}
}
